package rentel.logbook.persistence;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class DBService {

	private static java.util.logging.Logger logger = Logger.getLogger(
		DBService.class.getName()
	);
	
	/**
	 * Save item to the DB
	 * @param user
	 */
	public static void add(IRowBuilder builder) {
		
		Object row = builder.buildRow();
		
		insert(row);

	}
	
	/**
	 * Insert item to the DB
	 * @param row
	 * @throws SystemException 
	 * @throws IllegalStateException 
	 */
	private static void insert(Object row) {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		
		Transaction transaction = null;
		
		try {
			transaction = session.beginTransaction();

			session.save(row);
      
			transaction.commit();
			
		} catch (HibernateException e) {
			
			logger.log(Level.WARNING, "Error, when trying add row(" + row + ").");
			e.printStackTrace();
			
			if (transaction != null) {
				transaction.rollback();
			}

			// throw new IllegalStateException("Error, when trying add user.", e);

		}finally {
			session.close(); 
		}
	}
}
